package com.juku2024.juku.tools

import io.reactivex.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

object RxUtils {
    fun <T> doObservable(
        callback: (c: ObservableEmitter<T>) -> Unit,
        success: (T?) -> Unit,
        fail: (Throwable?) -> Unit
    ): Disposable {
        return Observable.create<T> {
            callback(it)
        }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                success(it)
            }, {
                fail(it)
            })
    }

    fun <T> doObservable(
        callback: (c: ObservableEmitter<T>) -> Unit,
        success: (T?) -> Unit
    ): Disposable {
        return doObservable(callback, success) {
            it?.printStackTrace()
        }
    }

    fun <T> doObservable(callback: (c: ObservableEmitter<T>) -> Unit): Disposable {
        return doObservable(callback, {
        }, {
            it?.printStackTrace()
        })
    }

    fun delay(
        delay: Long,
        success: (Long) -> Unit
    ): Disposable {
        return Flowable.timer(delay, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                success(it)
            }, {
                it?.printStackTrace()
            })
    }

    fun timer(
        delay: Long,
        exc: (c: Long) -> Unit,
        success: (Long) -> Unit
    ): Disposable {
        return Flowable.timer(delay, TimeUnit.MILLISECONDS)
            .doOnNext {
                exc(it)
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                success(it)
            }, {
                it?.printStackTrace()
            })
    }
    fun timer(
        delay: Long,
        success: (Long) -> Unit
    ): Disposable {
        return Flowable.timer(delay, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                success(it)
            }, {
                it?.printStackTrace()
            })
    }
    fun interval(
        start: Long,
        count: Long,
        delay: Long,
        period: Long,
        success: (Long) -> Unit
    ): Disposable {
        return  Flowable.intervalRange(start, count, delay, period, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe ({
                success(it)
            }, {
                it?.printStackTrace()
            })
    }
}